package com.qf.servlet;

import com.qf.entity.User;
import com.qf.service.UserService;
import com.qf.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * --- 缘分让我们相遇乱世以外 ---
 *
 * @author SJY
 * @date 2024/11/8
 * @desc
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    UserService userService = new UserServiceImpl( );
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // req.setCharacterEncoding("utf-8");
        // 接受请求数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println("username = " + username);
        System.out.println("password = " + password);

        // 调用方法处理业务
        User user = userService.login(username, password);

        //resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        //做出响应
        if (user != null){
            // 向请求域中存登录的人
            // req.setAttribute("user",user);

            // 获得session
            req.getSession().setAttribute("user",user);

            // 登录成功,将请求转发到ListServlet,让其查询全部
            //req.getRequestDispatcher("/user/list").forward(req,resp);

            // 携带有数据,重定向跳转servlet,请求域数据无法传递,ListServlet取不出数据
            // 使用了session后,请求转发还是重定向都可以取出session数据
            resp.sendRedirect("/user/list");

        }else {
            // out.write("<html>");
            // out.write("<head>");
            // out.write("<title>主页</title>");
            // out.write("</head>");
            // out.write("<body>");
            // out.write("<h1 style='color:red'>登录失败,用户名或密码错误</h1>");
            // out.write("</body>");
            // out.write("</html>");

            // 单独跳转页面,请求转发可以
            // req.getRequestDispatcher("/error.jsp").forward(req,resp);
            // 单独跳转页面,重定向也可以
            resp.sendRedirect("/error.jsp");
        }


    }
}
